package org.andlisp.android;

import android.content.ServiceConnection;
import android.content.Context;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;

public class ServerStatusPreference extends CheckBoxPreference
  implements LispService.SCServerStatusListener, Preference.OnPreferenceChangeListener,
             LispService.SCServerStartListener, LispService.SCServerStopListener
{

  final static String LOG_TAG = "ServerStatusPreference";
  private Context mCtx;
  
  public ServerStatusPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
    mCtx = context;
    setEnabled(false);
    LispService.getServerStatusAsync(mCtx, this);
  }
  
  public void onSCServerStatus(IBinder binder, boolean running) {
    Log.d(LOG_TAG, "onSCServerStatus(" + String.valueOf(running) + ")");
    setChecked(running);
    setOnPreferenceChangeListener(this);
    setEnabled(true);
  }

  public void onSCServerStart(IBinder binder, boolean success) {
    Log.d(LOG_TAG, "onSCServerStart(" + String.valueOf(success) + ")");
    setChecked(LispService.getServerStatus(binder));
    setOnPreferenceChangeListener(this);
    setEnabled(true);
  }

  public void onSCServerStop(IBinder binder) {
    Log.d(LOG_TAG, "onSCServerStop()");
    setChecked(LispService.getServerStatus(binder));
    setOnPreferenceChangeListener(this);
    setEnabled(true);
  }

  public boolean onPreferenceChange(Preference p, Object value) {
    Log.d(LOG_TAG, "onPreferenceChange(" + p.toString() + ", " + value.toString() + ")");
    boolean start = false;
    if (value instanceof Boolean) {
      start = ((Boolean)value).booleanValue();
    } else {
      Log.e("ServerStatus", "value is not Boolean");
      return false;
    }
    setOnPreferenceChangeListener(null);
    setEnabled(false);
    if (start) {
      LispService.startServerAsync(mCtx, SafePreferenceManager.getInt(mCtx, "Port", 10000), this);
    } else {
      LispService.stopServerAsync(mCtx, this);
    }
    return true;
  }
}
